package io.gitee.kotle.android.utils

import android.graphics.Bitmap
import android.widget.ImageView
import androidx.annotation.IntRange
import coil.*
import coil.request.ImageRequest
import coil.size.Size
import coil.transform.Transformation
import com.google.android.renderscript.Range2d
import com.google.android.renderscript.Toolkit
import io.gitee.kotle.android.BaseGlobalConst
import io.gitee.kotle.android.utils.glide.GlideBlurTransformation

/**
 *
 * 描述：
 *
 * 创建人：jiale.wei
 * 创建时间：2021/11/23 3:46 下午
 *
 */


/**
 * 加载图片
 */
inline fun ImageView.setImageByCoil(
    data: Any?,
    imageLoader: ImageLoader = BaseGlobalConst.coilImageLoader,
    builder: (ImageRequest.Builder) -> Unit = {}
) = load(data, imageLoader, builder)

/**
 * 清除或者取消加载
 */
fun ImageView.clearImageByCoil() = dispose()

/**
 * 一个下载drawable的简单例子
 */
suspend inline fun String.downloadAsDrawableByCoil(
    imageLoader: ImageLoader = BaseGlobalConst.coilImageLoader,
    builder: ImageRequest.Builder.() -> Unit = {}
) =
    imageLoader.execute(
        ImageRequest.Builder(BaseGlobalConst.app)
            .data(this)
            .also(builder)
            .build()
    ).drawable

open class BlurTransformation @JvmOverloads constructor(
    @IntRange(from = 1, to = 25) val radius: Int = 10,
    val restriction: Range2d? = null
) : GlideBlurTransformation(), Transformation {

    override val cacheKey: String
        get() = "${BlurTransformation::class.java.name}-$radius-$restriction"

    override suspend fun transform(input: Bitmap, size: Size): Bitmap {
        return Toolkit.blur(input, radius, restriction)
    }

    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        return other is BlurTransformation &&
                radius == other.radius &&
                restriction === other.restriction
    }

    override fun hashCode(): Int {
        var result = 0
        result = 31 * result + radius.hashCode()
        result = 31 * result + restriction.hashCode()
        return result
    }

    override fun toString(): String {
        return "BlurTransformation(radius=$radius, sampling=$restriction)"
    }
}